package com.example.project.service;

import com.example.project.model.Sale;
import com.example.project.repository.SaleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SaleServiceItem implements SaleService {
    @Autowired
    private SaleRepository saleRepository;

    //获取所有销售数据
    @Override
    public List<Sale> getAllSale() {
        return saleRepository.findAll();
    }

    //保存
    @Override
    public void saveSale(Sale sale) {
        this.saleRepository.save(sale);
    }

    //获取指定id
    @Override
    public Sale getSaleId(long id) {
        Optional<Sale> optional = saleRepository.findById(id);
        Sale sale = null;

        if (optional.isPresent()) {
            sale = optional.get();
        } else {
            throw new RuntimeException("找不到指定设备的id : " + id);
        }
        return sale;
    }

    //删除
    @Override
    public void deleteSaleById(long id) {
        this.saleRepository.deleteById(id);
    }

    @Override
    public Page<Sale> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        //设置排序参数，升序ASC/降序DESC？
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();

        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        return this.saleRepository.findAll(pageable);
    }


}
